package com.mzm.remoting;

import java.net.URL;

import org.springframework.util.StringUtils;

import com.mzm.api.MzmAdminFacade;
import com.mzm.remoting.invoker.HttpInvokerServices;

/**
 * A generic remote accessor to MZM's services.
 * 
 * @author Daniel Orr
 * 
 */
public class MzmServices implements IMzmServices {

	private RemoteObjectLocator objectLocator;

	private String host;
	private String urlTemplate;

	private MzmAdminFacade mzmAdminFacade;

	public static IMzmServices resolveServices(URL url) {
		if (url.toString().contains("/xfire/")) {
			//return new XFireServices(url.getHost() + ":" + url.getPort());
		} else if (url.toString().contains("/remoting/")) {
			return new HttpInvokerServices(url.getHost() + ":" + url.getPort());
			// return new BurlapServices(url.getHost() + ":" + url.getPort());
		}
		throw new IllegalArgumentException("Given url does not match any connection method.");
	}

//	public static IMzmServices getXFireValireServices(String host) {
//		return new XFireServices(host);
//	}

	public static IMzmServices getHttpInvokerServices(String host) {
		return new HttpInvokerServices(host);
	}

	protected MzmServices(RemoteObjectLocator objectLocator, String host, String urlTemplate) {
		this.objectLocator = objectLocator;
		this.host = host;
		this.urlTemplate = urlTemplate;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object getRemoteObject(String url, Class clax) {
		return objectLocator.getRemoteObject(url, clax);
	}

	@Override
	public MzmAdminFacade getMzmAdminFacade() {
		if (mzmAdminFacade == null) {
			mzmAdminFacade = (MzmAdminFacade) objectLocator.getRemoteObject(
					getUrlString("mzmAdminFacade"), MzmAdminFacade.class);
		}
		return mzmAdminFacade;
	}

	@Override
	public Object getGenericService(String serviceId, Class<?> serviceInterface) {
		return objectLocator.getRemoteObject(getUrlString(serviceId), serviceInterface);
	}

	private String getUrlString(String beanName) {
		String s = StringUtils.replace(urlTemplate, "[host]", host);
		s = StringUtils.replace(s, "[bean]", beanName);
		return s;
	}

}
